import { Injectable, HttpException, HttpStatus } from "@nestjs/common";
import { InjectRepository } from "@nestjs/typeorm";
import { AuthService } from "src/modules/common/auth/services/auth/auth.service";
import { AccountEntity } from "src/modules/system/account/entities/account.entity";
import { Repository } from "typeorm";
import { LoginInput } from "../../dto/login.input";

@Injectable()
export class LoginService {
  constructor (
    @InjectRepository(AccountEntity)
    private readonly accountRepository: Repository<AccountEntity>,
    private readonly authService: AuthService,
  ) { }

  async login(loginInput: LoginInput): Promise<AccountEntity> {
    const { username, password } = loginInput;
    const account = await this.accountRepository.findOne({ where: { username, password } });
    if (account) {
      return Object.assign(account, { 
        token: this.authService.generateToken(account),
      });
    } else {
      throw new HttpException('账号或密码错误', HttpStatus.OK);
    }
  }
}